﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Hotel_Admin.Common;
using HOTEL.Dao;
using Hotel.Util;
using Hotel.Domain;
using Hotel_Admin.Web.Common;
using System.Web.UI.HtmlControls;

namespace Hotel_Admin
{
    public partial class NhomPhanQuyen : Authentication
    {
        private PagesDao pageDao = new PagesDao();
        private GroupPerDao grDao = new GroupPerDao();
        private NhomNguoiDungDao nhomnguoidungDao = new NhomNguoiDungDao();
        protected void Page_Load(object sender, EventArgs e)
        {
            CheckViewPermission();
            if (!Page.IsPostBack)
            {
                LoadNhomNguoiDung();
            }
        }
        private void CheckViewPermission()
        {
            if (!HasViewPermission(Pages.NhomPhanQuyen.GetHashCode()))
            {
                Redirect(WebURL.UrlWebDinie);
            }
        }
        
        
        protected void LoadNhomNguoiDung()
        {
            var nhomnguoidungs = nhomnguoidungDao.GetList();
            gvList.DataSource = nhomnguoidungs;
            gvList.DataBind();
        }
        
        protected Group Group
        {
            get
            {

                return Session[SessionKey.SessionCurrenGroup] as Group;
            }
            set
            {
                Session[SessionKey.SessionCurrenGroup] = value;
            }
        }
        protected bool IsValidData()
        {
            if (String.IsNullOrEmpty(txtTenNhóm.Text.Trim()))
            {
                ShowError("Tên nhóm người dùng không được trống", txtTenNhóm.ClientID);
                return false;
            }
            return true;
        }

        protected void gvList_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            var require = e.CommandName;
            var id = ConvertUtil.ToInteger(e.CommandArgument.ToString());
            if (!id.HasValue) return;
            
            switch (require)
            {

                case "EditItem":
                    var nhomnguoidung = nhomnguoidungDao.Get(id.Value);
                    if (nhomnguoidung != null)
                    {
                        Session[SessionKey.SessionCurrenGroup] = nhomnguoidung;
                        BindDataForGrid();
                        Group = nhomnguoidung;
                    }
                    break;

            }
        }

        protected void DoSave()
        {
            List<GroupPermission> listPermission = new List<GroupPermission>();
            for (var i = 0; i < grdPermission.Rows.Count; i++)
            {
                var row = grdPermission.Rows[i];
                var hdPageid = row.FindControl("hdPageId") as HiddenField;
                var chkRead = (HtmlInputCheckBox)row.FindControl("chkRead");
                var chkInsert = (HtmlInputCheckBox)row.FindControl("chkInsert");
                var chkUpdate = (HtmlInputCheckBox)row.FindControl("chkUpdate");
                var chkDelete = (HtmlInputCheckBox)row.FindControl("chkDelete");
                for (int j = 1; j <= 4; j++)
                {
                    var gr = new GroupPermission
                    {
                        GroupId = Group.Id,
                        PageId = int.Parse(hdPageid.Value),
                        Active=true
                    };
                    if (j == 1)
                    {
                        gr.Permission = chkRead.Checked ? PERMISSION.View.GetHashCode() : 0;
                        if (gr.Permission != 0)
                            listPermission.Add(gr);
                    }
                    else if (j == 2)
                    {
                        gr.Permission = chkInsert.Checked ? PERMISSION.Insert.GetHashCode() : 0;
                        if (gr.Permission != 0)
                            listPermission.Add(gr);
                    }
                    else if (j ==3)
                    {
                        gr.Permission = chkDelete.Checked ? PERMISSION.Delete.GetHashCode() : 0;
                        if (gr.Permission != 0)
                            listPermission.Add(gr);
                    }
                    else
                    {
                        gr.Permission = chkUpdate.Checked ? PERMISSION.Update.GetHashCode() : 0;
                        if (gr.Permission != 0)
                            listPermission.Add(gr);
                    }
                }
            }
            var msg = grDao.UpdateList(listPermission, Group);
            if (msg.MsgType != MessageType.Info)
            {
                ShowError("Phân quyền không thành công");
                CloseWaitingDialog();
            }
            else
            {
                ShowInfor("Phân quyền thành công");
                DoHuy();
                CloseWaitingDialog();
            }
        }
        protected void btnSave_Click(object sender, EventArgs e)
        {
            DoSave();
        }
        protected void DoHuy()
        {
            LoadNhomNguoiDung();
            upNhomNguoiDung.Update();
            divgrPer.Visible = false;
            upGird.Update();
        }
        protected void btnHuy_Click(object sender, EventArgs e)
        {
            DoHuy();
            CloseWaitingDialog();
        }

        private List<GroupPermission> groupPermissions;
        #region bỏ
        //protected override void OnPreRender(EventArgs e)
        //{
        //    base.OnPreRender(e);

        //    // Bind data for grid permission
        //    BindDataForGrid();
            
        //    // Show function of group
        //    if ((groupPermissions == null) || (groupPermissions.Count <= 0))
        //        return;
        //    foreach (var gp in groupPermissions)
        //    {
        //        for (var i = 0; i < grdPermission.Rows.Count; i++)
        //        {
        //            var row = grdPermission.Rows[i];
        //            var chkFunctionId = (HtmlInputCheckBox)row.FindControl("chkFunctionId");
        //            if (gp.PageId != int.Parse(chkFunctionId.Value))
        //                continue;

        //            chkFunctionId.Checked = true;
        //            switch (gp.Permission)
        //            {
        //                case 1:
        //                    {
        //                        var chkRead = (HtmlInputCheckBox)grdPermission.Rows[i].FindControl("chkRead");
        //                        chkRead.Checked = true;
        //                        break;
        //                    }
        //                case 2:
        //                    {
        //                        var chkInsert = (HtmlInputCheckBox)grdPermission.Rows[i].FindControl("chkInsert");
        //                        chkInsert.Checked = true;
        //                        break;
        //                    }
        //                case 3:
        //                    {
        //                        var chkUpdate = (HtmlInputCheckBox)grdPermission.Rows[i].FindControl("chkUpdate");
        //                        chkUpdate.Checked = true;
        //                        break;
        //                    }
        //                case 4:
        //                    {
        //                        var chkDelete = (HtmlInputCheckBox)grdPermission.Rows[i].FindControl("chkDelete");
        //                        chkDelete.Checked = true;
        //                        break;
        //                    }
        //            }
        //            break;
        //        }
        //    }
        //}
        #endregion
        #region Properties

        public List<GroupPermission> GroupPermissions
        {
            get
            {
                groupPermissions = new List<GroupPermission>();

                for (var i = 0; i < grdPermission.Rows.Count; i++)
                {
                    var row = grdPermission.Rows[i];
                    var chkFunctionId = (HtmlInputCheckBox)row.FindControl("chkFunctionId");

                    if (!chkFunctionId.Checked)
                        continue;

                    var chkRead = (HtmlInputCheckBox)grdPermission.Rows[i].FindControl("chkRead");
                    if (chkRead.Checked)
                    {
                        var gp = GetGroupPermission(int.Parse(chkFunctionId.Value), int.Parse(chkRead.Value));
                        groupPermissions.Add(gp);
                    }

                    var chkInsert = (HtmlInputCheckBox)grdPermission.Rows[i].FindControl("chkInsert");
                    if (chkInsert.Checked)
                    {
                        var gp = GetGroupPermission(int.Parse(chkFunctionId.Value), int.Parse(chkInsert.Value));
                        groupPermissions.Add(gp);
                    }

                    var chkUpdate = (HtmlInputCheckBox)grdPermission.Rows[i].FindControl("chkUpdate");
                    if (chkUpdate.Checked)
                    {
                        var gp = GetGroupPermission(int.Parse(chkFunctionId.Value), int.Parse(chkUpdate.Value));
                        groupPermissions.Add(gp);
                    }

                    var chkDelete = (HtmlInputCheckBox)grdPermission.Rows[i].FindControl("chkDelete");
                    if (!chkDelete.Checked)
                        continue;

                    var gpDel = GetGroupPermission(int.Parse(chkFunctionId.Value), int.Parse(chkDelete.Value));
                    groupPermissions.Add(gpDel);
                }
                return groupPermissions;
            }
            set
            {
                groupPermissions = value;
            }

        }

        #endregion

        protected GroupPermission GetGroupPermission(int functionId, int mash)
        {

            return new GroupPermission
            {
                PageId = functionId,
                Permission = mash
            };
        }

        private void BindDataForGrid()
        {
            var list = pageDao.Getlist();
            grdPermission.DataSource = list;
            grdPermission.PagerInforText = list.Count.ToString();
            grdPermission.DataBind();
            divgrPer.Visible = true;
            upGird.Update();
        }

        protected void grdPermission_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (!e.Row.RowType.Equals(DataControlRowType.DataRow)) return;
            var chkFunctionId = (HtmlInputCheckBox)e.Row.FindControl("chkFunctionId");
            var pages = grdPermission.DataSource as List<PAGE>;
            var page = pages[e.Row.RowIndex + grdPermission.PageIndex * grdPermission.PageSize];
            var chkRead = (HtmlInputCheckBox)e.Row.FindControl("chkRead");
            var chkInsert = (HtmlInputCheckBox)e.Row.FindControl("chkInsert");
            var chkUpdate = (HtmlInputCheckBox)e.Row.FindControl("chkUpdate");
            var chkDelete = (HtmlInputCheckBox)e.Row.FindControl("chkDelete");
            var hasViewcheck = grDao.HasPer(Group.Id, page.PageId, PERMISSION.View.GetHashCode());
            chkRead.Checked = hasViewcheck;
            var hasInsertcheck = grDao.HasPer(Group.Id, page.PageId, PERMISSION.Insert.GetHashCode());
            chkInsert.Checked = hasInsertcheck;
            var hasDeletecheck = grDao.HasPer(Group.Id, page.PageId, PERMISSION.Delete.GetHashCode());
            chkDelete.Checked = hasDeletecheck;
            var hasUpdatecheck = grDao.HasPer(Group.Id, page.PageId, PERMISSION.Update.GetHashCode());
            chkUpdate.Checked = hasUpdatecheck;
            if (hasViewcheck && hasInsertcheck && hasDeletecheck && hasUpdatecheck)
            {
                chkFunctionId.Checked = true;
            }
        }

    }
}